<template>
    <div class="product_list">
        <el-row :gutter="24" class="product_form">
            <el-form >
                <el-col :span="3" v-if="false">
                    <el-input v-model="key" placeholder="请输入付款人" icon="search"
                              @keyup.enter="init"></el-input>
                </el-col>
                <el-col :span="2" v-if="false">
                    <el-cascader :show-all-levels="false" placeholder="请选择付款方式" :options="payMethodOptions" v-model="selectedPayMethodOptions" ></el-cascader>
                </el-col>
                <el-col :span="3" v-if="false">
                    <el-cascader  :show-all-levels="false" placeholder="请选择收入类型" :options="payTypeOptions" v-model="selectedPayTypeOptions"></el-cascader>
                </el-col>
                <el-col :span="6">
                    <el-date-picker v-model="periods" type="daterange" range-separator="至" style="width: 100%;"  start-placeholder="开始日期" end-placeholder="结束日期" ></el-date-picker>
                </el-col>
                <el-col :span="7">
                    <el-button class="btn_orange"  icon="el-icon-search" @click="searchProduct">搜索</el-button>
                    <el-button class="btn_lightBrwon"   @click="onReset">重置</el-button>
                    <el-button class="btn_darkBrwon"   @click="handleDownload">导出数据</el-button>
                </el-col>
                <el-col :span="8">
                    <el-button class="btn_lightBrwon" @click="dateSearch(1)">上月</el-button>
                    <el-button class="btn_lightBrwon" @click="dateSearch(2)">今日</el-button>
                    <el-button class="btn_lightBrwon" @click="dateSearch(3)">本周</el-button>
                    <el-button class="btn_lightBrwon" @click="dateSearch(4)">本月</el-button>
                </el-col>
                <!--<el-col :span="3">-->
                <!--<el-cascader :show-all-levels="false" placeholder="请选择状态" :options="statusOptions" v-model="selectedStatusOptions"></el-cascader>-->
                <!--</el-col>-->
            </el-form>
        </el-row>
        <el-table class="product_table"  :data="dataList" show-summary :row-class-name="tableRowClassName"   :height="tableHeight">
            <!--<el-table-column type="index"></el-table-column>-->
            <el-table-column prop="date" label="日期" align="center" header-align="center" min-width="110px"></el-table-column>
            <el-table-column prop="receipt" label="收入金额" align="center" header-align="center"></el-table-column>
            <el-table-column prop="payment" label="支出金额" align="center" header-align="center"></el-table-column>
            <el-table-column prop="balance" label="收支差额" align="center" header-align="center"></el-table-column>
            <!--<el-table-column prop="payer" label="付款人/单位" align="center" header-align="center"></el-table-column>-->
            <!--<el-table-column prop="payMethod.name" label="收款方式" align="center" header-align="center"></el-table-column>-->
            <!--<el-table-column prop="payType.name" label="收入类型" align="center" header-align="center"></el-table-column>-->
            <!--<el-table-column prop="paymentFor" label="收款事由" align="center" header-align="center">-->
                <!--<template slot-scope="scope">-->
                    <!--<el-popover trigger="hover" placement="top">-->
                        <!--<div>{{scope.row.paymentFor}}</div>-->
                        <!--<div slot="reference" class="name-wrapper"><p class="grid_title">{{scope.row.paymentFor}} </p> </div>-->
                    <!--</el-popover>-->
                <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column prop="handleBy" label="经办人" align="center" header-align="center"></el-table-column>-->
            <!--<el-table-column prop="handleAt" :formatter="fmHandleAt" label="经办时间" align="center" header-align="center"></el-table-column>-->
            <!--<el-table-column prop="deleted" label="状态">-->
            <!--<template slot-scope="scope">-->
            <!--<p v-if="scope.row.deleted == '1'"  class="p-green">作废</p>-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column label="作废原因">-->
            <!--<template slot-scope="scope">-->
            <!--<el-popover trigger="hover" placement="top">-->
            <!--<span>{{scope.row.abandonCause}}</span>-->
            <!--<div slot="reference" class="name-wrapper"><p class="grid_title">{{scope.row.abandonCause}} </p> </div>-->
            <!--</el-popover>-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column prop="abandonBy" label="作废操作人"></el-table-column>-->
            <!--<el-table-column label="操作">-->
            <!--<template slot-scope="scope">-->
            <!--<el-button   v-if="scope.row.deleted=='0'" type="info"  @click="handleDel(scope.$index, scope.row)" >作废 </el-button>-->
            <!--</template>-->
            <!--</el-table-column>-->

        </el-table>
        <!--<el-pagination-->
                <!--@size-change="handleSizeChange"-->
                <!--@current-change="handleCurrentChange"-->
                <!--:current-page="page"-->
                <!--:page-sizes="pageSizes"-->
                <!--:page-size="pageSize"-->
                <!--layout=" sizes, prev, pager, next,total"-->
                <!--:total="total">-->
        <!--</el-pagination>-->

        <el-dialog
                title="作废原因"
                :visible.sync="dialogVisible"
                width="30%"
                center>
            <el-input v-model="abandonCause" type="textarea" style="border:1px #dddddd solid;" :rows="4" placeholder="请输入作废原因"></el-input>
            <span slot="footer" class="dialog-footer">
                 <el-button @click="dialogVisible = false">取 消</el-button>
                 <el-button class="btn_lightBrwon" @click="handleAbandon">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    import ReceiptDao from '@/api/ReceiptDao';
    import baseUtil from "../../utils/baseUtil";
    import {PayMethod,ReceiptType} from '../../utils/basicData'
    import Receipt from '@/model/receipt/Receipt';
    import Bill from '@/model/bill/Bill';
    import ExcelUtil from '../../utils/excelUtil'
    import DateUtil from '../../utils/dateUtil'

    let tableHeight =  Math.max(document.body.scrollHeight,document.documentElement.scrollHeight) - 229;
    export default {
        name:'receiptList',
        data(){
            return{
                tableHeight: tableHeight,
                infoStatus:null,
                dataList:[],
                exportDataList:[],
                payMethodOptions:baseUtil.getOptions(baseUtil.modelCopy(PayMethod)),
                payTypeOptions:baseUtil.getOptions(baseUtil.modelCopy(ReceiptType)),
                statusOptions:[
                    {value:'', label:'全部'},
                    {value:0, label:'正常'},
                    {value:1, label:'报废'}],
                selectedPayMethodOptions: [],
                selectedPayTypeOptions: [],
                selectedStatusOptions: [],
                key:null,
                periods:null,
                datePeriods:null,
                page:1,
                pageSize:15,
                pageSizes:[15,30,50],
                total:0,
                downloadLoading:false,
                dialogVisible:false,
                abandonCause:null,
                receipt:baseUtil.modelCopy(Receipt),
            }
        },
        methods:{
            dateSearch(flag) {
                let period = [];
                switch (flag){
                    case 1:period = DateUtil.getLastMonth();break;
                    case 2:period = DateUtil.getToday();break;
                    case 3:period = DateUtil.getThisWeek();break;
                    case 4:period = DateUtil.getThisMonth();break;
                }
                this.periods = null
                this.datePeriods = period
                this.init()
            },
            async  handleAbandon(){
                this.receipt.abandonCause = this.abandonCause
                this.receipt.abandonBy = this.$store.getters.user.username
                this.dialogVisible = false
                await  ReceiptDao.updateData({_id:this.receipt._id},{deleted:1,abandonCause:this.receipt.abandonCause,abandonBy:this.receipt.abandonBy})
                this.init();
            },
            tableRowClassName(value){
                let row = value.row
                if(row.deleted == '1'){
                    return 'warning-row';
                }
            },
            fmHandleAt(row, column){
                return this.fmUtil.fmDate(new Date(row.handleAt), 'yyyy.MM.dd')
            },
            handleChange(value) {
                this.init()
            },
            handleCurrentChange(val){
                this.page = val;
                this.init();
            },
            handleDel(index, row){
                this.abandonCause = null
                this.dialogVisible = true
                this.receipt = row
            },
            handleSizeChange(val){
                this.pageSize = val;
                this.init();
            },
            //重置
            onReset(){
                this.selectedPayMethodOptions = []
                this.selectedPayTypeOptions = []
                this.selectedStatusOptions = []
                this.key = null
                this.periods = null
                this.datePeriods = null
                this.page = 1;
                this.init();
            },
            //搜索
            searchProduct(){
                this.page = 1;
                this.datePeriods = null
                this.init();
            },
            async handleDownload() {
                this.downloadLoading = true
                const tHeader = ['日期', '收入金额', '支出金额', '收支差额']
                const filterVal = ['date', 'receipt', 'payment', 'balance']
                const list = this.dataList
                const fileName = '收支总账'
                await ExcelUtil.exportJsonToExcel(tHeader,filterVal,list,fileName)
                this.downloadLoading = false
            },
            searchParam(){
                let searchParam = {}, arrParam = {},methodQuery = {},typeQuery = {},dateQuery = {},statusQuery = {};
                let arrKey = [];
                let paramKey = this.baseUtil.modelCopy(this.key);
                let methodKey = this.baseUtil.modelCopy(this.selectedPayMethodOptions);
                let typeKey = this.baseUtil.modelCopy(this.selectedPayTypeOptions);
                let dateKey = this.baseUtil.modelCopy(this.periods);
                let datePeriodsKey = this.datePeriods
                let statusKey = this.baseUtil.modelCopy(this.selectedStatusOptions)

                if(this.baseUtil.isNotBlankObj(dateKey) && dateKey.length > 0) {
                    let date =  new Date(dateKey[1])
                    date.setHours(23,59,59)
                    dateKey[1] = date
                    dateQuery = {handleAt:{$gte:  new Date(dateKey[0]),$lte:dateKey[1]}}
                }else if(this.baseUtil.isNotBlankObj(datePeriodsKey) && datePeriodsKey.length > 0) {
                    dateQuery = {handleAt:{$gte:  datePeriodsKey[0],$lte:datePeriodsKey[1]}}
                }
                if(this.baseUtil.isNotBlankObjs(statusKey)){
                    let   status = statusKey[0]
                    statusQuery = {deleted:status}
                }
                if(this.baseUtil.isNotBlank(paramKey)) {
                    let key = eval("/"+paramKey+"/");
                    arrKey.push({payer: {$regex:key}})
                    arrParam = { $or : arrKey  }
                }
                if(this.baseUtil.isNotBlankObjs(methodKey)){
                    let payMethod =methodKey[methodKey.length-1]
                    methodQuery = {payMethod:payMethod}
                }
                if(this.baseUtil.isNotBlankObjs(typeKey)){
                    let payType =typeKey[typeKey.length-1]
                    typeQuery = {payType:payType}
                }
                if(JSON.stringify(dateQuery) != "{}" || JSON.stringify(arrParam) != "{}" || JSON.stringify(methodQuery) != "{}" || JSON.stringify(typeQuery) != "{}" ||  JSON.stringify(statusQuery) != "{}"  ) {
                    searchParam = {$and :[dateQuery,arrParam,methodQuery,typeQuery,statusQuery,{deleted:0}]}
                }else searchParam = {deleted:0}
                return searchParam
            },
            handleData(bills) {
                let map = {},billList = []
                bills.map(m => {
                    let handleAt = this.fmUtil.fmDate(new Date(m.handleAt), 'yyyy.MM.dd')
                    if(this.baseUtil.isBlank(map[handleAt])) {
                        let bill = baseUtil.modelCopy(Bill);
                        bill.date = handleAt
                        bill.receipt = m.money ? parseInt(m.money):0
                        bill.payment = m.payment ? parseInt(m.payment):0
                        map[handleAt] = bill
                        billList.push(bill)
                    }else {
                        let bill = map[handleAt]
                        bill.receipt += m.money? parseInt(m.money):0
                        bill.payment += m.payment? parseInt(m.payment):0
                    }
                })
                billList.map(m => { m.balance = parseInt(parseInt(m.receipt) - parseInt(m.payment)) })
                return billList
            },
            async init(){
                let searchParam = this.searchParam()
                // let page = parseInt(this.page);
                // let pageSize = parseInt(this.pageSize)
                // let startPages =( page - 1 )* pageSize
                // await ReceiptDao.count(searchParam).then((m)=>{this.total = m})
                let bills = await ReceiptDao.findListNoPage(searchParam,{"handleAt":-1})
                if(this.baseUtil.isNotBlankObj(bills) && bills.length > 0) {
                    this.dataList = this.handleData(bills)
                }else {
                    this.dataList = [];
                    this.$message({showClose: true,message: '没有查询到任何数据',type: 'error'});
                }
            }
        },
        activated(){
            this.init();
        }
    }
</script>
<style>
</style>
